﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.DesktopClient;
using EzDesk.DesktopClient.Model;
using System.Reflection;
using EzDesk.Generic;
using System.IO;

using EzDesk.Generic;
using System.Runtime.Serialization.Formatters.Binary;

namespace EzDesk.DesktopClient
{
    public class DataStorage
    {
        protected readonly string _relatedPath = "user\\data";

        public string GetFilePath(string name, string storeType)
        {
            string folderName = Path.Combine(PathHelp.CurrentPath, _relatedPath, storeType);
            if (!Directory.Exists(folderName))
                Directory.CreateDirectory(folderName);
            return Path.Combine(folderName, name);
        }

        public DataStorage Save(object data, string name, string storeType)
        {
            string filePath = this.GetFilePath(name, storeType);
            using (FileStream stream = File.Create(filePath))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, data);
                stream.Close();
            }
            return this;
        }
        public T Load<T>(string name, string storeType)
        {
            string filePath = this.GetFilePath(name, storeType);

            if (File.Exists(filePath))
            {
                using (FileStream stream = File.Open(filePath, FileMode.Open))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    try
                    {
                        T data = (T)formatter.Deserialize(stream);
                        return data;
                    }
                    catch(Exception ex)
                    {
                        return default(T);
                    }
                    finally
                    {
                        stream.Close();
                    }
                }
            }
            else
                return default(T);
        }
    }
}
